"""Auxiliary GUI routines."""
import datetime as dt
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from analysis import indicators as ii
import system.navalasystem as na
from misc import misc

def PopulateStockTable(t, aStock, refDt=None):
    """Populates a QTableWidget with stock names, descriptions, and indicators.
    
    Arguments:
        t -- QTableWidget
        aStock -- rows from the stock database table
        refDt -- =(indicators.readRefDt at 23h59). Reference datetime
        
    Accesses indicators._aa and .flagsChecked to get indicators to add as columns."""
    
    if refDt is None:
        refDt = ii.readRefDt #misc.EndOfDay(dt.datetime.today())
    
    inds = ii.GetCheckedIndicators()
    nind = len(inds)
    nc = 2+nind
    

    t.clear()
    t.sortItems(-1)
    t.setRowCount(len(aStock))
    t.setColumnCount(nc)
    a = ["Symbol", "Description"]+[x.name for x in inds]
    t.setHorizontalHeaderLabels(a)

    for i, row in enumerate(aStock):
        item = QTableWidgetItem(row[4]) # name
        data = QVariant([row[0], row[4], row[3]]) # id, name, symbol
        item.setData(Qt.UserRole, data) # id
        t.setItem(i, 0, item)
        item = QTableWidgetItem(row[5]) # description
        # item.setTextAlignment(Qt.AlignCenter)
        t.setItem(i, 1, item)
#            item = QTableWidgetItem("%5.3f" % row[6]) # sanity
#            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
#            t.setItem(i, 2, item)

        j = 2 # Column index
        for ind in inds:
            Q = na.vala.store.GetTimeData(ind, row[4], refDt, refDt)
            if len(Q) == 0:
                value = -1
            else:
                value = Q.y[0]
            item = QTableWidgetItem(ind.FormatValue(value))
            t.setItem(i, j, item)
            j += 1
    
    t.resizeColumnsToContents()
